package red.yancloud.www.ui.read

import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import com.tencent.smtt.sdk.WebSettings
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import kotlinx.android.synthetic.main.activity_read_pdf.*
import org.greenrobot.eventbus.EventBus
import red.yancloud.www.R
import red.yancloud.www.base.BaseActivity
import red.yancloud.www.ui.dialog.BookReadSettingDialog
import red.yancloud.www.util.ScreenUtils
import red.yancloud.www.util.ToastUtils

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/7/8 18:08
 * E_Mail：yh131412hys@163.com
 * Describe：pdf阅读界面
 * Change：
 * @Version：V1.0
 */
class PdfReadActivity : AppCompatActivity(), View.OnClickListener {

    private val TAG = "PdfReadActivity"

//    private lateinit var mWebView:X5WebView
    private var mScreenWidth: Int = 0
    private var mScreenHeight: Int = 0
    private var isShow:Boolean = false
    private var bookName:String=""
    private var bookId:String=""
    private var content:String=""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_read_pdf)

        mScreenWidth = ScreenUtils.getScreenWidth()
        mScreenHeight = ScreenUtils.getRealHeight()

        initData()
        initView()
    }


    private fun initData() {

//        mWebView = X5WebView(this, null)
//        pdfReadActivity_cL.addView(
//            mWebView, FrameLayout.LayoutParams(
//                FrameLayout.LayoutParams.FILL_PARENT,
//                FrameLayout.LayoutParams.FILL_PARENT
//            )
//        )
        mScreenWidth = ScreenUtils.getScreenWidth()
        mScreenHeight = ScreenUtils.getRealHeight()

        bookName = intent.getStringExtra("title")
        bookId = intent.getStringExtra("bookId")
        content = intent.getStringExtra("content")

        title_tv.text = bookName

        webSetting()
    }

    private fun initView() {

        back_iv.setOnClickListener(this)
        share_iv.setOnClickListener(this)
        readPdfActivity_webView.setOnTouchListener(object :View.OnTouchListener{
            @SuppressLint("ClickableViewAccessibility")
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {

                Log.d("onTouchEvent", event!!.action.toString())

                if (event.action == MotionEvent.ACTION_UP && getTouchLocation(event.x, event.y) == SETTING_AREA) {

                    if (!isFastClick()) {

                        isShow = !isShow
                        title_layout.visibility= if (isShow) View.VISIBLE else View.GONE
                    }
                    return true
                }
                return false
            }
        })
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.back_iv -> {
                title_layout.visibility=View.GONE
                finish()
            }
            R.id.share_iv -> {

                title_layout.visibility=View.GONE

                val image = UMImage(this, R.mipmap.ic_launcher)
                val web = UMWeb(/*"http://www.yancloud.red/Yancloudapp/article/?bid=$bookId"*/"http://www.yancloud.red/Portal/Book/info/?id=$bookId") //切记切记 这里分享的链接必须是http开头
                web.title = bookName//标题
                web.setThumb(image)  //缩略图
                web.description = content//描述

                ShareAction(this).withMedia(image).withMedia(web)
                    .setDisplayList(
                        SHARE_MEDIA.SINA,
                        SHARE_MEDIA.QQ,SHARE_MEDIA.QZONE,
                        SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
                        SHARE_MEDIA.MORE)
                    .setCallback(umShareListener).open()
            }
        }
    }

    private val umShareListener = object : UMShareListener {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        override fun onStart(platform: SHARE_MEDIA) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        override fun onResult(platform: SHARE_MEDIA) {

            ToastUtils.showToast("分享成功了")
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        override fun onError(platform: SHARE_MEDIA, t: Throwable) {

            ToastUtils.showToast("分享失败" + t.message)
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        override fun onCancel(platform: SHARE_MEDIA) {

        }
    }

    private val MIN_DELAY_TIME = 1000  // 两次点击间隔不能少于1000ms
    private var lastClickTime: Long = 0

    private fun isFastClick(): Boolean {
        var flag = true
        val currentClickTime = System.currentTimeMillis()
        if (currentClickTime - lastClickTime >= MIN_DELAY_TIME) {
            flag = false
        }
        lastClickTime = currentClickTime
        return flag
    }

    // 点击页面区域
    private val PREVIOUS_AREA = 1
    private val NEXT_AREA = 2
    private val SETTING_AREA = 3

    /**
     * 判断点击的区域
     *
     * @param x
     * @param y
     * @return
     */
    private fun getTouchLocation(x: Float, y: Float): Int {
        if (x > mScreenWidth / 4 && x < mScreenWidth * 3 / 4
            && y > mScreenHeight / 4 && y < mScreenHeight * 3 / 4
        ) {
            return SETTING_AREA
        } else if (x > mScreenWidth / 2) {
            return NEXT_AREA
        }
        return PREVIOUS_AREA
    }


    /**
     * 网页配置参数设置
     */
    @SuppressLint("SetJavaScriptEnabled")
    @TargetApi(Build.VERSION_CODES.M)
    private fun webSetting() {
//        val webSettings: WebSettings = readActivity_webView.settings
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
//        }
//        webSettings.javaScriptCanOpenWindowsAutomatically = true
//        webSettings.javaScriptEnabled = true
//        readActivity_webView.isFocusable = true
//        readActivity_webView.setBackgroundColor(0x00ffffff)
//        readActivity_webView.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
//
//        // 是否支持viewport属性，默认值 false
//        // 页面通过`<meta name="viewport" ... />`自适应手机屏幕
//        webSettings.useWideViewPort = true
//        // 是否使用overview mode加载页面，默认值 false
//        // 当页面宽度大于WebView宽度时，缩小使页面宽度等于WebView宽度
//        webSettings.loadWithOverviewMode = true
//        // 布局算法
//        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL
//
//        // 缩放(zoom)
//        webSettings.setSupportZoom(true)          // 是否支持缩放
//        webSettings.builtInZoomControls = true // 是否使用内置缩放机制
//        webSettings.displayZoomControls = true  // 是否显示内置缩放控件

        val webSetting = readPdfActivity_webView.settings
        // 是否可访问本地文件，默认值 true
        webSetting.allowFileAccess = true
        // 布局算法
//        webSetting.layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL;
//         适应内容大小
        webSetting.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
//        适应屏幕，内容将自动缩放
//        webSetting.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN

        webSetting.setSupportZoom(true)
        webSetting.builtInZoomControls = true
        // 是否支持viewport属性，默认值 false
        // 页面通过`<meta name="viewport" ... />`自适应手机屏幕
        webSetting.useWideViewPort = true
        webSetting.setSupportMultipleWindows(false)
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true)
        // webSetting.setDatabaseEnabled(true);
        webSetting.domStorageEnabled = true
        webSetting.javaScriptEnabled = true
        webSetting.setGeolocationEnabled(true)
        webSetting.setAppCacheMaxSize(java.lang.Long.MAX_VALUE)
        webSetting.setAppCachePath(this.getDir("appcache", 0).path)
        webSetting.databasePath = this.getDir("databases", 0).path
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0).path)
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.pluginState = WebSettings.PluginState.ON_DEMAND
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // webSetting.setPreFectch(true);

//        webSetting.setSupportZoom(false)
//        // 是否使用内置缩放机制
//        webSetting.builtInZoomControls = false
        // 是否显示内置缩放控
        webSetting.displayZoomControls = false
// 是否支持viewport属性，默认值 false
// 页面通过`<meta name="viewport" ... />`自适应手机屏幕
        webSetting.useWideViewPort = true
// 是否使用overview mode加载页面，默认值 false
// 当页面宽度大于WebView宽度时，缩小使页面宽度等于WebView宽度
        webSetting.loadWithOverviewMode = true

        val time = System.currentTimeMillis()
        readPdfActivity_webView.loadUrl(intent.getStringExtra("firstbookpdfurl"))

//        TbsLog.d("time-cost", "cost time: " + (System.currentTimeMillis() - time))
//        CookieSyncManager.createInstance(this)
//        CookieSyncManager.getInstance().sync()

        readPdfActivity_webView.scaleX=1.2f
        readPdfActivity_webView.scrollY=1
        readPdfActivity_webView.setOnScrollChangeListener(object :View.OnScrollChangeListener{
            override fun onScrollChange(v: View?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) {

                Log.d(TAG,"${readPdfActivity_webView.scaleY}")
                Log.d(TAG, "scrollX:$scrollX--scrollY:$scrollY--oldScrollX:$oldScrollX--oldScrollY:$oldScrollY")
            }
        })
    }
}
